import { Request, Response } from 'express';
import { Message, User } from '../models';
import { Op } from 'sequelize';
import { AppError } from '../utils/errorHandler';

// 发送消息
export const sendMessage = async (req: Request, res: Response): Promise<void> => {
    try {
        const { receiverId, content, type = 'text' } = req.body;
        const senderId = req.user?.id;
        if (!senderId) {
            res.status(401).json({ message: '未授权' });
            return;
        }
        const receiver = await User.findByPk(receiverId);
        if (!receiver) {
            res.status(404).json({ message: '接收者不存在' });
            return;
        }
        const message = await Message.create({ senderId, receiverId, content, type, status: 'sent' });
        res.status(201).json(message);
        return;
    } catch (error) {
        console.error('发送消息失败:', error);
        res.status(500).json({ message: '发送消息失败' });
    }
};

// 获取与特定用户的聊天历史
export const getChatHistory = async (req: Request, res: Response): Promise<void> => {
    try {
        const { userId } = req.params;
        const currentUserId = req.user?.id;
        const { page = 1, limit = 20 } = req.query;
        const offset = (Number(page) - 1) * Number(limit);

        if (!currentUserId) {
            throw new AppError('未授权', 401);
        }

        const messages = await Message.findAll({
            where: {
                [Op.or]: [
                    { senderId: currentUserId, receiverId: userId },
                    { senderId: userId, receiverId: currentUserId }
                ]
            },
            include: [
                {
                    model: User,
                    as: 'sender',
                    attributes: ['id', 'username', 'avatar']
                },
                {
                    model: User,
                    as: 'receiver',
                    attributes: ['id', 'username', 'avatar']
                }
            ],
            order: [['createdAt', 'DESC']],
            limit: Number(limit),
            offset
        });

        const total = await Message.count({
            where: {
                [Op.or]: [
                    { senderId: currentUserId, receiverId: userId },
                    { senderId: userId, receiverId: currentUserId }
                ]
            }
        });

        res.json({
            total,
            pages: Math.ceil(total / Number(limit)),
            currentPage: Number(page),
            messages
        });
        return;
    } catch (error) {
        console.error('获取聊天历史失败:', error);
        res.status(500).json({ message: '获取聊天历史失败' });
    }
};

// 获取未读消息
export const getUnreadMessages = async (req: Request, res: Response): Promise<void> => {
    try {
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const messages = await Message.findAll({
            where: {
                receiverId: userId,
                status: 'sent'
            },
            include: [
                {
                    model: User,
                    as: 'sender',
                    attributes: ['id', 'username', 'avatar']
                }
            ],
            order: [['createdAt', 'DESC']]
        });

        res.json(messages);
        return;
    } catch (error) {
        console.error('获取未读消息失败:', error);
        res.status(500).json({ message: '获取未读消息失败' });
    }
};

// 标记消息为已读
export const markAsRead = async (req: Request, res: Response): Promise<void> => {
    try {
        const { messageIds } = req.body;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        await Message.update(
            { status: 'read' },
            {
                where: {
                    id: messageIds,
                    receiverId: userId,
                    status: 'sent'
                }
            }
        );

        res.json({ message: '消息已标记为已读' });
        return;
    } catch (error) {
        console.error('标记消息为已读失败:', error);
        res.status(500).json({ message: '标记消息为已读失败' });
    }
};

// 删除消息
export const deleteMessage = async (req: Request, res: Response): Promise<void> => {
    try {
        const { messageId } = req.params;
        const userId = req.user?.id;

        if (!userId) {
            throw new AppError('未授权', 401);
        }

        const message = await Message.findByPk(messageId);
        if (!message) {
            throw new AppError('消息不存在', 404);
        }

        if (message.senderId !== userId && message.receiverId !== userId) {
            throw new AppError('无权删除此消息', 403);
        }

        await message.destroy();
        res.json({ message: '消息删除成功' });
        return;
    } catch (error) {
        console.error('删除消息失败:', error);
        res.status(500).json({ message: '删除消息失败' });
    }
}; 